package action.upload;

import java.io.File;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.inject.Container;

import common.impl.exception.ServiceException;
import common.interf.IErrorHandle;
import common.interf.IFileHandle;
import common.interf.IImage;
import common.interf.IServletHandle;

public class ImageCBAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	private String filePath="/upload/images";
	private IImage iImage;
	private IServletHandle servletHandle;
	private IFileHandle fileHandle;
	private IErrorHandle errorHandle;
	private File file;
	private String fileContentType;
	private String fileFileName;
	private Integer size=0;
	private Integer width=0;
	private Integer height=0;
	private String cb;
	
	public void setiImage(IImage iImage) {
		this.iImage = iImage;
	}

	public void setServletHandle(IServletHandle servletHandle) {
		this.servletHandle = servletHandle;
	}
	
	public void setFileHandle(IFileHandle fileHandle) {
		this.fileHandle = fileHandle;
	}
	
	public void setErrorHandle(IErrorHandle errorHandle) {
		this.errorHandle = errorHandle;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}
	
	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	
	public void setCb(String cb) {
		this.cb = cb;
	}
	public void save(){
		String s="";
		try{
			if(!iImage.checkImage(file, size, width, height)){
				throw new ServiceException("ERR-0020");
			}
			s = fileHandle.saveUploadFile(file, ServletActionContext.getServletContext().getRealPath(filePath), fileFileName);
			String serverUrl = servletHandle.getServerPath(ServletActionContext.getRequest());
			s = serverUrl + filePath + "/" + s;
		}catch(Exception e){ 
			s = errorHandle.handleErr(e);
		}
		if(!StringUtils.isEmpty(cb))
			s = "<script>" + cb + "('" + s + "');</script>";
		servletHandle.writeToClient(ServletActionContext.getResponse(), s);
	}
	
}
